class WebSocketClient {
    constructor(url) {
      this.url = url; // WebSocket 服务端地址
      this.ws = null; // WebSocket 实例
      this.listeners = {}; // 事件监听器
    }
  
    // 初始化 WebSocket
    connect() {
      if (this.ws) {
        console.warn('WebSocket 已连接');
        return;
      }
  
      this.ws = new WebSocket(this.url);
  
      this.ws.onopen = () => {
        console.log('WebSocket 已连接');
        this.emit('open');
      };
  
      this.ws.onmessage = (event) => {
        console.log('收到消息:', event.data);
        const message = JSON.parse(event.data);
        this.emit('message', message);
      };
  
      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
        this.emit('error', error);
      };
  
      this.ws.onclose = () => {
        console.log('WebSocket 已关闭');
        this.ws = null;
        this.emit('close');
      };
    }
  
    // 发送消息
    send(data) {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(data));
      } else {
        console.error('WebSocket 未连接，无法发送消息');
      }
    }
  
    // 添加事件监听器
    on(event, callback) {
      if (!this.listeners[event]) {
        this.listeners[event] = [];
      }
      this.listeners[event].push(callback);
    }
  
    // 触发事件
    emit(event, data) {
      if (this.listeners[event]) {
        this.listeners[event].forEach((callback) => callback(data));
      }
    }
  
    // 关闭 WebSocket 连接
    close() {
      if (this.ws) {
        this.ws.close();
      }
    }
  }
  
  // 导出 WebSocket 客户端实例
  export default new WebSocketClient(import.meta.env.VITE_APP_WS_URL || 'ws://localhost:8080');